package com.lzyjkz.quick_components.filter;

import com.lzyjkz.quick_components.constant.RedisBucketConstant;
import com.lzyjkz.quick_components.exceptions.LoginExpiredException;
import com.lzyjkz.quick_components.service.TokenService;
import com.lzyjkz.quick_components.utils.JwtUtil;
import com.lzyjkz.quick_components.utils.RedisCache;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.IOException;

@Component
@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final RedisCache redisCache;
    private final JwtUtil jwtUtil;
    private final TokenService tokenService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String Bearer = request.getHeader("Authorization");
        log.info("请求方法：{}, 请求路径：{}, 请求令牌：{}" , request.getMethod(), request.getRequestURL().toString(), Bearer);
        if (Bearer == null || !Bearer.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = Bearer.substring(7);

        UserDetails loginUser = tokenService.getUserDetails(token);

        if (loginUser == null) {
            throw new LoginExpiredException();
        }

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
